package com.jinyu.controller;

import com.jinyu.service.SelectKwLEDService;
import onbon.y2.Y2DynamicManager;
import onbon.y2.Y2Env;
import onbon.y2.Y2Screen;
import onbon.y2.play.DynamicArea;
import onbon.y2.play.DynamicAreaPicUnit;
import onbon.y2.play.DynamicPlayFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.List;
@RestController
@RequestMapping("/creatPh")
@EnableScheduling // 1.开启定时任务
public class ImageGenera {
    @Autowired
    private SelectKwLEDService selectKwLEDService;
    @ResponseBody
    @PostMapping("creatPh")
    @Scheduled(cron = "0/1800 * * * * ?")   //定时任务
    public void creatPh() {
        int ledAllCount = selectKwLEDService.getLedAllCount();
        Integer i = ledAllCount / 16 + (ledAllCount % 16 == 0 ? 0 :1);// 向上取整
//        System.out.println(i);
        for ( Integer j = 1; j < i+1; j++) {
            List<Map<String, Object>> ledAll = selectKwLEDService.getLedAll((j-1)*16+1,16);
            String[][] strings = dateCreate(ledAll);
            String s = new String();
            s = "C:/excel/"+j.toString()+".png";
            myGraphicsGeneration(strings,s,j);
        }

        openPh(i);
        System.out.println("节目发送成功！");

    }
//
//    @ResponseBody
//    @GetMapping("creatPh")
//    public List<Map<String,Object>> getLedAll(Integer offset,Integer size) {
//
//        return selectKwLEDService.getLedAll(10,10);
//    }

    /**
     * @Description: 数据处理，把list集合处理成2维数组，注意set集合无序
     * @Param: ArrayList集合，jdbc的工具类查询出来
     * @return: 二维数组
     * @Author:
     */
    public String[][] dateCreate(java.util.List<Map<String, Object>> date) {

        //在list集合中首位添加一个元素（所有的key）
        List<Map<String, Object>> maps = new ArrayList<>();
//        List<Map<String, Object>> maps1 = new ArrayList<>();

        Map<String, Object> stringObjectMap = date.get(0);
        Set<String> keys = stringObjectMap.keySet();
        Map<String,Object> map1 = new HashMap<String,Object>();
        map1.put("0","状态");
        map1.put("1","物料");
        map1.put("2","批次");
        map1.put("3","库位");
        map1.put("4","数量");


        //这样排序才对，要改成汉字，这里注意set是无序的
//        Integer a = 0;
//        for (String key : keys) {
//            String s = a.toString();
//            map1.put(s,key);
//            a++;
//        }
        maps.add(map1);


//        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(maps));
//        String s1 = objects.toString();
//        System.out.println(s1);


        //将date集合添加到新集合
        maps.addAll(date);


        //二维数组的第二个数组长度，行数 查询的条数+1（列头）4
        int size = maps.size();
//        System.out.println(size);
        String[][] z = new String[size][];
        for (int i = 0; i < z.length; i++) {
            Map m = (Map) maps.get(i);
            Set set = m.keySet();
            z[i] = new String[m.size()];
            Iterator it = set.iterator();
            for (int j = 0; it.hasNext(); j++) {
                String s = (String) it.next();
                if (m.get(s) != null) {
                    z[i][j] = m.get(s).toString();
                }
            }
        }
        return z;
    }
    /**
     * 生成图片
     * @param cellsValue 以二维数组形式存放 表格里面的值
     * @param path 文件保存路径
     */
    public void myGraphicsGeneration(String cellsValue[][],String path,Integer i){
        // 字体大小
        int fontTitileSize =11;
        // 横线的行数
        int totalrow = cellsValue.length+2;
        // 竖线的行数
        int totalcol = 0;
        if (cellsValue[0] != null){
            totalcol = cellsValue[0].length-1;
        }
        // 图片宽度
        int imageWidth =448;
        // 行高
        int rowheight= 23;
        // 图片高度
        int imageHeight = 430;
        // 起始高度
        int startHeight = 0;
        // 起始宽度
        int startWidth = 10;
        // 单元格宽度
        int colwidth = (int)((imageWidth-20)/totalcol);
        BufferedImage image = new BufferedImage(imageWidth,imageHeight,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.black);
        graphics.fillRect(0,0,imageWidth,imageHeight);
//        graphics.setColor(new Color(220,240,240));

        //画横线
        for(int j=0;j < totalrow;j++){
            graphics.setColor(Color.WHITE);
            graphics.drawLine(startWidth,startHeight+(j)*rowheight,startWidth+colwidth*totalcol,startHeight+(j)*rowheight);
        }
        //画竖线

        graphics.setColor(Color.WHITE);
        graphics.drawLine(startWidth+0*colwidth,startHeight,startWidth+0*colwidth,startHeight+rowheight*(totalrow-1));
        for(int k=1;k<totalcol+1;k++){
            graphics.setColor(Color.WHITE);
            graphics.drawLine(startWidth+k*colwidth,23,startWidth+k*colwidth,startHeight+rowheight*(totalrow-1));
            if (k==4){
                graphics.setColor(Color.WHITE);
                graphics.drawLine(startWidth+k*colwidth,startHeight,startWidth+k*colwidth,startHeight+rowheight*(totalrow-1));
            }
        }
        //设置字体
        Font font  = new Font("宋体",Font.BOLD,15);
        graphics.setFont(font);

        //写入内容
        graphics.setColor(Color.RED);
        graphics.drawString(i.toString(),startWidth+5,startHeight+rowheight-5);
        for(int n=0;n<cellsValue.length;n++){
            if (cellsValue[n][0].equals("YELLOW")) {
                for(int l=1;l<cellsValue[n].length;l++){
                    String s = cellsValue[n][l];
                    if (n == 0){
                        font = new Font("宋体",Font.BOLD,fontTitileSize);
                        graphics.setFont(font);
                        graphics.setColor(Color.GREEN);
                    }else if (n > 0){
                        font = new Font("宋体",Font.PLAIN,fontTitileSize);
                        graphics.setFont(font);
                        graphics.setColor(Color.YELLOW);
                    }
                    graphics.drawString(cellsValue[n][l].toString(),startWidth+colwidth*(l-1)+5,startHeight+rowheight*(n+2)-10);
                }
            }else {
                for(int l=1;l<cellsValue[n].length;l++){
                    String s = cellsValue[n][l];
                    if (n == 0){
                        font = new Font("宋体",Font.BOLD,fontTitileSize);
                        graphics.setFont(font);
                        graphics.setColor(Color.GREEN);
                    }else if (n > 0){
                        font = new Font("宋体",Font.PLAIN,fontTitileSize);
                        graphics.setFont(font);
                        graphics.setColor(Color.GREEN);
                    }
                    graphics.drawString(cellsValue[n][l].toString(),startWidth+colwidth*(l-1)+5,startHeight+rowheight*(n+2)-10);
                }
            }

        }
        // 保存图片
        createImage(image,path);
    }





    /**
     * 将图片保存到指定位置
     * @param image 缓冲文件类
     * @param fileLocation 文件位置
     */
    public void createImage(BufferedImage image, String fileLocation){
        try{
//            fileLocation = "D:/desktop/123.png";
            FileOutputStream fos = new FileOutputStream(fileLocation);
            ImageIO.write(image,"png",fos);
        } catch (Exception e){
            e.printStackTrace();
        }
    }


    private static String url = "10.13.7.102";
    public void openPh(Integer i){
        // 初始化API，此操作只在程序启动时候执行一次，多次执行会出现内存错误
//        Y2Env.initial("src/main/resources/log.properties",true);

//        soundArea();

        try {
            sendDynamic(i);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendDynamic(Integer i)throws Exception{
        // 创建screen对象，用于与控制卡的交互
        Y2Screen screen = new Y2Screen(url);

        // 登入
        // 登入账号和密码默认都为guest
        screen.login("guest","guest");

        // 创建动态区管理
        Y2DynamicManager dyn = screen.dynamic();

        // 创建动态区文件
        DynamicPlayFile file = new DynamicPlayFile();


        // 于动态区文件中新增一个动态区域
        DynamicArea dynamicArea2 = file.createArea(0, 0, 896, 50, 0);
        DynamicAreaPicUnit dynamicAreaPicUnit = dynamicArea2.addImage("C:/excel/header.png");
        DynamicArea dynamicArea = file.createArea(0,50,448,430,1);
            dynamicAreaPicUnit.setStayTime(40);
            dynamicAreaPicUnit.animationType(0);
            dynamicAreaPicUnit.animationSpeed(16);
        for (int j = 1; j < i+1; j+=2){
            DynamicAreaPicUnit dynamicAreaPicUnit1 = dynamicArea.addImage("C:/excel/" + j + "" + ".png");
            dynamicAreaPicUnit1.setStayTime(40);
            dynamicAreaPicUnit1.animationType(0);
            dynamicAreaPicUnit1.animationSpeed(16);
        }
        DynamicArea dynamicArea1 = file.createArea(448, 50, 448, 430, 2);
        // 动态区中添加显示内容，可以是图片，也可以是字符串

        for (int j = 2; j < i+1; j+=2){
            DynamicAreaPicUnit dynamicAreaPicUnit1 = dynamicArea1.addImage("C:/excel/" + j + "" + ".png");
            dynamicAreaPicUnit1.setStayTime(40);
            dynamicAreaPicUnit1.animationType(0);
            dynamicAreaPicUnit1.animationSpeed(16);
        }

        // 更新动态区
        dyn.write(file);

        // 设置动态区断电保存
//        dyn.save("0");

        // 登出
        screen.logout();
    }
}

